package zebbe.android.opengl;

import javax.microedition.khronos.opengles.GL10;

import zebbe.android.opengl.screens.GameLoop;
import zebbe.android.opengl.support.GameActivity;
import zebbe.android.opengl.support.GameListener;
import zebbe.android.opengl.support.GameScreen;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends GameActivity implements GameListener {

	GameScreen screen;
	Simulation simulation = null;

	long start = System.nanoTime();
	int frames = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setGameListener(this);

		if (savedInstanceState != null
				&& savedInstanceState.containsKey("simulation"))
			simulation = (Simulation) savedInstanceState
					.getSerializable("simulation");

		Log.d("Space Invaders", "created, simulation: " + (simulation != null));

	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (screen instanceof GameLoop)
			outState.putSerializable("simulation",
					((GameLoop) screen).simulation);
		Log.d("Space Invaders", "saved game state");
	}

	@Override
	public void onPause() {
		super.onPause();
		if (screen != null)
			screen.dispose();
		if (screen instanceof GameLoop)
			simulation = ((GameLoop) screen).simulation;
		Log.d("Space Invaders", "paused");
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.d("Space Invaders", "resumed");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d("Space Invaders", "destroyed");
	}

	@Override
	public void setup(GameActivity activity, GL10 gl) {
		if (simulation != null) {
			screen = new GameLoop(gl, activity, simulation);
			simulation = null;
			Log.d("Space Invaders", "resuming previous game");
		} else {
			// screen = new StartScreen(gl, activity);
			// Log.d( "Space Invaders", "starting a new game" );
			screen = new GameLoop(gl, activity);
		}

	}

	@Override
	public void mainLoopIteration(GameActivity activity, GL10 gl) {
		
		screen.update(activity);
		screen.render(gl, activity);

		if( screen.isDone() )
        {
                screen.dispose();
        }
		
		frames++;
		if (System.nanoTime() - start > 1000000000) {
			Log.d("Space Invaders", "fps: " + frames);
			frames = 0;
			start = System.nanoTime();
		}

	}

}
